﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Server.Demo
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window,jacSocket.jacEvent 
    {
        jacSocket.JFormat jfm = new jacSocket.JFormat();

        public Window1()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(Window1_Loaded);
        }

        void Window1_Loaded(object sender, RoutedEventArgs e)
        {
            jc = new jacSocket.JControler(this, 4502);
            jc.StartupSocketServer();
            this.Title = "Server is running!";
        }

        #region jacEvent Members
        jacSocket.JControler jc;
        List<jacSocket.ClientSocketPacket> clients = new List<jacSocket.ClientSocketPacket>();

        public void userEnter(object data)
        {
            clients.Add((jacSocket.ClientSocketPacket)data);
        }

        public void gotData(object data)
        {
            //deSerialize
            var dt = jfm.Deserialize<msgclass>(data.ToString());
            //change the sendTime value
            dt.sendTime = DateTime.Now;

            //send to all clients
            for (int i = 0; i <= clients.Count - 1; i++)
            {
                jc.SendMessage(jfm.ToJson<msgclass>(dt), clients[i]);
            }
        }

        public void delUser(object data)
        {
            if (clients.Contains((jacSocket.ClientSocketPacket)data))
            {
                clients.Remove((jacSocket.ClientSocketPacket)data);
            }
        }

        #endregion
    }
}
